<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Manager</title>
<style type="text/css">
.row {
    border-bottom: 1px red dotted;
    padding: 10px 0px;
}

.lspan {
    font-weight: bold;
    width: 150px;
    display: inline-block;
    margin-left: 10px;
}

#maskDiv {
    position: absolute;
    border: 0px green solid;
    width:100%;
    height: 100%;
    z-index: 30;
    background: rgb(0, 0, 0, 0.2);
    top:0px;
    left: 0px;
    display: none;
}

#maskDivLoading {
    position: absolute;
    border: 0px green solid;
    width:100%;
    height: 100%;
    z-index: 30;
    background: white;
    top:0px;
    left: 0px;
}

.img-stage{
    top: 50%;
    left: 50%;
    position: absolute;
    background:red;
}

#maskDivLoading img {
    top: 50%;
    left: 50%;
    height: 200px;
    width: 200px;
    margin-top : -120px;
    margin-left : -100px;
    position: absolute;
}


#uploadDivLoading img {
    top: 50%;
    left: 50%;
    border:0px;
    height: 30px;
    width: 30px;
}
.buttonClass {
    border: 1px orange solid;
    background: white;
    color: orange;
    font-size: 16px;
    padding: 6px;
}

</style>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script src="js/jqueryui/jquery-ui.js"></script>
<link href="js/jqueryui/jquery-ui.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="js/datatables.css">
<script type="text/javascript" charset="utf8" src="js/datatables.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/fixedHeader.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="js/dataTables.fixedHeader.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/select.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="js/dataTables.select.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/buttons.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="js/dataTables.buttons.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/videojs/video-js.min.css">
<script type="text/javascript" charset="utf8" src="js/videojs/video.min.js"></script>
<script type="text/javascript" charset="utf8" src="js/qr/jquery.qrcode.min.js"></script>
<link rel="stylesheet" href="css/base.css" />
<link rel="stylesheet" type="text/css" href="css/fileUpload.css">
<script type="text/javascript" src="js/fileUpload.js"></script>
<script type="text/javascript">
function getQueryParam(variable) {
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return '';
}
Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}

function autoNextHandler(obj) {
	var autoPlayIntervalId = null;
	if(obj.checked) {
		autoPlayIntervalId = setInterval(function() {
			var player = document.getElementById('myAudio');
            if(player && player.ended) {
            	console.log("go next song...")
            	nextHandler();
            }
        }, 10000);
	} else {
		if(autoPlayIntervalId) {
			clearInterval(autoPlayIntervalId);
		}
	}
}

function utf16to8(str) {
    var out, i, len, c; 
    out = ""; 
    len = str.length; 
	for(i = 0; i < len; i++) { 
	    c = str.charCodeAt(i); 
	    if ((c >= 0x0001) && (c <= 0x007F)) { 
	        out += str.charAt(i); 
	    } else if (c > 0x07FF) { 
	        out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); 
	        out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); 
	        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); 
	    } else { 
	        out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); 
	        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); 
	    } 
	} 
    return out; 
}
function qrHander(url) {
	$( "#qrcode" ).html('');
	var urlPrefix =window.location.protocol + "//" +window.location.host;
	console.log(urlPrefix + url);
	$('#qrcode').qrcode({
        render:"canvas",
        width: 200,
        height: 200,
        correctLevel:0, 
        text: urlPrefix + url,
        background:"#00FF00",
        foreground:"black",
    });
	
	$( "#qrDiv" ).dialog("open");
}

function urlCopyHandler(relativeUrl, msgSpanId) {
	var url = window.location.protocol + "//" +window.location.host + relativeUrl;
	$('#' + msgSpanId).html('')
    var urlInput = document.createElement('input');
    var copyError = null;
    urlInput.value = url;
    document.body.appendChild(urlInput);
    urlInput.select();
    try {
        document.execCommand("Copy", false, null);
    } catch (e) {
        copyError = e;
    } finally {
        document.body.removeChild(urlInput);
        if (copyError != null){
            alert("Failed to Copy" + "\n url : " + url);
        } else{
            $('#' + msgSpanId).html("Copy Done.")
            $('#' + msgSpanId).show();
            setTimeout(function() {
                $('#' + msgSpanId).hide();
             },3000);
        }
    }
}




function pathHandler(path, parent) {
	var navi = "";
	if(parent) {
		// C:/study/2019/mp3
		var np = parent.split("/");
		var preParent = "";
		var prePath = "";
		for(var i = 0; i < np.length; i++) {
			preParent = "";
			for(var j = 0; j < i; j++) {
				if(preParent === "") {
					preParent = np[j];
				} else {
					preParent = preParent + "/" +  np[j];
				}
				
			}
			if(i == 0) {
				preParent = "Root";
				prePath = "";
			} else {
				prePath = np[i];
			}
				
			navi = navi + "<a href='#' onclick='pathHandler(" + '"' + prePath+ '","'+  preParent + '"' + ");'>" + np[i] + "</a>" + "&nbsp;/&nbsp;"
		}
	}
	 $("#pathHidden").val(parent + '/'+ path);
	 if(mytable) {
		 mytable.ajax.reload();
	 }
     $("#navigator").html(navi + path);
     //window.location.href=window.location.href; 
    // window.location.reload;
}

function downloadHandler(obj, fileName) {
	
	var url = '/file/download/' + fileName;
	url = encodeURI(url);
	this.obj.href = url;
    /* $.ajax({
        url: url,
        type: 'GET',
        beforeSend : function(req) {
            
        },
         success:function(data){
             
             console.log(data);
             
         },
         error:function(data){
                alert("Fail");
         }
    }); */
}

function previewHandler(name) {
	$('#autoNextSpan').hide();
	var pos = name.lastIndexOf('.');
    var isMp3 = false;
    var isMp4 = false;
    var isImage = false;
    var isText = false;
    var audioExt = ["mp3", "wma", "wav"];
    var imageExt = ["png", "jpeg", "jpg", "gif", "bmp"];
    var textExt =["txt", "xml", "log", "java", "properties", "md","bat", "sh", "cmd", "html", "htm", "js", "json", "sql","bak", "css", "xhtml", "jsp", "h", "cpp", "php", "asp", "aspx", "jx"];
    if(pos != -1) {
           var ext = name.substring(pos + 1);
           
           audioExt.forEach(v=> {
        	   if(v === ext) {
        		   isMp3 = true;
        	   }
           });
          if(ext === 'mp4') {
               isMp4 = true;
           } else {
        	   for(var i = 0; i < imageExt.length; i++) {
        		   if(ext.toLowerCase() === imageExt[i]) {
        			   isImage = true;
        			   break;
        		   }
        	   }
        	   if(!isImage) {
        		   for(var i = 0; i < textExt.length; i++) {
                       if(ext.toLowerCase() === textExt[i]) {
                           isText = true;
                           break;
                       }
                   }
        	   }
        	   
        	   
           }
    }
    var cd = $('#pathHidden').val();
    if(cd === '') {
        cd = getQueryParam("path");
    }
    var url = '/file/download/' + name + "?dp=inline&path=" + cd;
    url = encodeURI(url);
    if(isMp3) {
    	$('#autoNextSpan').show();
        var audioHtml = "<audio id='myAudio' src='" + url + "' " +  "controls='controls' autoplay='autoplay'  preload='auto'>";
        audioHtml = audioHtml + "Your browser does not support the audio element.";
        audioHtml = audioHtml + "</audio>"
        
        $('#preview').html(audioHtml);
        
    } else if(isMp4) {
        /* var videoHtml = "<video width='320' height='240' src='" + url + "' " +  "controls='controls' autoplay='autoplay'>";
        videoHtml = videoHtml + "Your browser does not support the video element.";
        videoHtml = videoHtml + "</video>" */
        url = encodeURI(url);
        var videoHtml = "<iframe id='player' style='padding: 0px;margin: 0px;border: 0px;' width='100%' height='330px' src='player.html?path=" + url +"'></iframe>"
        $('#preview').html(videoHtml);
    } else if(isImage) {
         var viewerHtml = "<iframe id='viewer' style='padding: 0px;margin: 0px;border: 0px;' width='100%' height='510px' src='viewer.html?path=" + url +"'></iframe>"
         $('#preview').html(viewerHtml);
    } else if(isText) {
    	var hash = url.indexOf('#');
    	if(hash != -1) {
    		 url = url.replace(/#/g, "%23")
    		//url = url.substring(0, hash) + '%23' + url.substring(hash + 1);
    	}
    	 var viewerHtml = "<iframe id='textViewer' style='padding: 0px;margin: 0px;border: 0px; overflow: hidden; width: 100%; height: 500px;' src='textViewer.html?path=" + url +"'></iframe>"
    	 //var viewerHtml = "<iframe id='textViewer' style='padding: 0px;margin: 0px;border: 0px;' width='100%' height='510px' src='" + url +"'></iframe>"
         $('#preview').html(viewerHtml);
    }
}


function updateHandler(id) {
	$('#umsgs').html('');
	$('#preview').html('');
	var item = $('#table_id').dataTable().fnGetData(id - 1);
	// preview:
	previewHandler(item.name);
	$('#fileName').val(item.name);
	$('#size').val(item.size);
	$( "#fileUpdateDiv" ).dialog( "open" );
	
	 var currentIndex = id - 1;
	 
	 // save current index to hidden
	 $('#indexHidden').val(currentIndex);
	 
     if(currentIndex == 0) {
         $("#preBtn" ).button( "disable" );
         $("#nextBtn" ).button( "enable" );
     } else {
         $("#nextBtn" ).button( "enable" );
         $("#preBtn" ).button( "enable" );
         var realTable = $('#table_id').dataTable();
         var allItems = realTable.fnGetData();
         if(currentIndex == allItems.length - 1) {
             $("#nextBtn" ).button( "disable" );
         }
     }
}

function nextHandler() {
    $('#umsgs').html('');
    var currentIndex = parseInt($('#indexHidden').val());
    var realTable = $('#table_id').dataTable();
    var allItems = realTable.fnGetData();
    currentIndex = currentIndex + 1;
    
    if(currentIndex >= allItems.length ) {
    	currentIndex = allItems.length - 1;
    	$("#nextBtn" ).button( "disable" );
    	$("#preBtn" ).button( "enable" );
    } else {
    	$("#nextBtn" ).button( "enable" );
        $("#preBtn" ).button( "enable" );
    }
    
    $('#indexHidden').val(currentIndex);
    
    var item = realTable.fnGetData(currentIndex);
    if(!item) {
    	return;
    }
    $('#fileName').val(item.name);
    $('#size').val(item.size);
    // preview:
    previewHandler(item.name);
}

function preHandler() {
    $('#umsgs').html('');
    var currentIndex = parseInt($('#indexHidden').val());
    currentIndex = currentIndex - 1;
    if(currentIndex <= 0) {
    	currentIndex = 0;
    	$("#nextBtn" ).button( "enable" );
        $("#preBtn" ).button( "disable" );
    } else {
    	$("#nextBtn" ).button( "enable" );
        $("#preBtn" ).button( "enable" );
    }
    $('#indexHidden').val(currentIndex);
    var realTable = $('#table_id').dataTable();
    var item = realTable.fnGetData(currentIndex);
    if(!item) {
        return;
    }
    $('#fileName').val(item.name);
    $('#size').val(item.size);
    // preview:
    previewHandler(item.name);
}

function doUpdate() {
    var index = $('#indexHidden').val();
    var email = $('#email').val();
    var phone = $('#phone').val();
    var status = $('#status').val();
    var creationTime = $('#creationTime').val();
    var loginName = $('#loginName').val();
    var userinfo = {
            "loginName" : loginName,
            "userEmail" : email,
            "userPhone" : phone,
            "userStatus" : status
    };
    
    var appJson = "application/json";
    $.ajax({
        url: '/user/update',
        type: 'POST',
        contentType: appJson,
        dataType: 'json',
        data: JSON.stringify(userinfo),
        beforeSend : function(req) {

        },
         success:function(data){
             var mymsg = data.data.msg || data.message;
             var dataCode = data.code;
             if(dataCode == '0') {
            	 $('#umsgs').html('<span style="color:green">'+ 'Update Successfully.'+ '</span>')
            	 var realTable = $('#table_id').dataTable();
            	var rowData = realTable.fnGetData(index);
            	rowData.userPhone = phone;
            	rowData.userEmail = email;
            	rowData.userStatus = status;
            	rowData.userCreateTime = creationTime;
            	realTable.fnDraw(false);
             } else {
            	 
            	 $('#umsgs').html('<span style="color:red">'+ 'Failed to update.' + '</span>')
             }
             
             
         },
         error:function(data){
                alert("Fail");
         }
    });
}

function doDelete() {
	var index = $('#indexHidden').val();
	var loginName = $('#loginName').val();
   var realTable = $('#table_id').dataTable();
   //realTable.fnDeleteRow(index);//删除行
   
   var appJson = "application/json";
   $.ajax({
       url: '/user/delete/' + loginName,
       type: 'DELETE',
       contentType: appJson,
       dataType: 'json',
       data: '',
       beforeSend : function(req) {

       },
        success:function(data){
            var mymsg = data.data.msg || data.message;
            var dataCode = data.code;
            if(dataCode == '0') {
                $('#umsgs').html('<span style="color:green">'+ 'Delete Successfully.'+ '</span>')
                var node = realTable.fnGetNodes(index);
                node.style = "font-size: 18px;font-weight: bold;color: orange;text-decoration:line-through";
                realTable.fnDraw(false);
                
            } else {
                
                $('#umsgs').html('<span style="color:red">'+ 'Failed to Delete.' + '</span>')
            }
            
            
        },
        error:function(data){
               alert("Fail");
        }
   });
}

function closeHandler() {
	$('#fileUpdateDiv').hide();
	$('#maskDiv').hide();
	
}

</script>

</head>
<body>
<div>Location: <span id="navigator">Root</span></div>
<table id="table_id" class="display">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Size</th>
            <th>Update Time</th>
            <th>Operation</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>
<!-- 
<div id="fileUpdateDiv" style="background-color:#e3e3e3; position:absolute; z-index:31; top:50%;left:50%; width:500px; height:500px; margin-top:-250px; margin-left:-250px; border:2px solid green">
 -->

<div id="fileUpdateDiv">
	<div id="messages" class="msg">
	    <div id="umsgs" style="margin-left: 10px">
	     
	    </div>
	</div>
	<div id="row" class="row">
	    <span id="lspan" class="lspan">
	        Name: 
	    </span>
	    <span id="cspan">
	        <input type="text" size="40" name="name" readonly="readonly" id="fileName"/>
	        
	        <span id="autoNextSpan" style="display: none">
	        &nbsp;<label for='autoNext'>
	        <input id='autoNext' type='checkbox' onclick='autoNextHandler(this);' >Auto Play</label>
	        </span>
	        
	        <span id="textSpan" style="display: none">
	        &nbsp;&nbsp;&nbsp;
	        <input type="button" id="viewText" class="buttonClass" onclick="viewText();return false;" value="View">
	         &nbsp;
	        <input type="button" id="editText" class="buttonClass" onclick="editText();return false;" value="Edit">
	        </span>
	    </span>
	</div>

	<div id="preview" class="row">
        
        
	</div>
	<input type="hidden" id="indexHidden"/>
</div>

<!-- upload div start  -->
<div id="createFolderDiv">
    <div id="row" class="row">
        <span id="lspan" class="lspan">
            Current Directory: 
        </span>
        <span id="currentDirecoty">
            
        </span>
    </div>
    <div id="row" class="row">
        <span id="lspan" class="lspan">
            Folder Name: 
        </span>
        <span id="cspan">
            <input type="text" name="folderName" id="folderName"/>
        </span>
    </div>
    <div id="row" class="row">
       <span id="lspan" class="lspan">
           
        </span>
        <div id="uploadDivLoading">
            <img alt="" src="images/sloading.gif">
            
        </div>
        <div id="cdmsgs">
        
        </div>
    </div>
    
    
</div>
<!-- upload div end  -->

<!-- upload div start  -->
<div id="uploadDiv">
    <div id="row" class="row">
        <span id="lspan" class="lspan">
            Current Directory:
        </span>
        <span id="currentDirecoty2">

        </span>
    </div>

    <div class="fileBox">
        <p class="fileInputP vm">
            <i>选择文件</i>
            <input type="file" multiple id="fileInput" />
        </p>
        <span id="fileSpan" class="vm">或者将文件拖到此处</span>
        <div class="mask"></div>
    </div>

    <table width="90%" border="1" class="fileList_parent">
        <thead>
        <tr>
            <th>Name</th>
            <th>Extension</th>
            <th>Size</th>
            <th>Operation</th>
            <th>Message</th>
        </tr>
        </thead>

        <tbody class="fileList">
        </tbody>

    </table>
</div>
<!-- upload div end  -->
<div id="maskDiv" >

</div>

<div id="maskDivLoading">
        <img alt="" src="images/loading.gif">
</div>

<div id="qrDiv" style="display: none;">
    <div id="qrcode">
    </div>
</div>

<input type="hidden" id="pathHidden" value=""/>
</body>

</html>